<template>
  <div v-if="loginSuccess" class="score-container">
      <h3>推荐横屏观看</h3>
    <el-collapse :accordion="true" v-model="activeNames">
      <el-collapse-item v-for="term in termGrade" :title="term.termName" :name="term.termName">
        <template #title>
          <div class="term-name">
            {{ term.termName }}
          </div>
        </template>
        <GradeTable :grades="term.grades"/>
      </el-collapse-item>
    </el-collapse>
  </div>
  <div v-else class="login-container">
    <el-form @submit.native.prevent :onsubmit="handleSubmit" class="login-form" :model="form" :rules="rules" ref="form" label-position="top">
      <h2 class="form-title">登录</h2>
      <el-form-item prop="password">
        <el-input type="password" v-model="form.password" placeholder="请输入教务网密码" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="captcha">
        <div class="captcha-container">
          <el-input v-model="form.captcha" placeholder="请输入验证码" autocomplete="off"></el-input>
          <img :src="'data:image/jpg;base64,' + verifyCodeBase64" alt="验证码" @click="refreshCaptcha"
               class="captcha-img"/>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" class="submit-btn">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script lang="ts">
import GradeTable from "./components/GradeTable.vue";
import {CheckStatus, GetScore, GetVerifyCodeImage} from "@/api/score";
import {GradeVO, QueryScoreDTO} from "@/model/score";
import {ElMessage} from "element-plus";
import {h} from "vue";

export default {
  name: 'GradeView',
  components: {GradeTable},
  data() {
    return {
      loginSuccess: false,
      verifyCodeBase64: '',
      token: '',
      form: {
        password: '',
        captcha: '',
      },
      rules: {
        password: [{required: true, message: '请输入教务网密码', trigger: 'blur'}],
        captcha: [{required: true, message: '请输入验证码', trigger: 'blur'}],
      },
      activeNames: [''],
      terms: ["大一上", "大一下", "大二上", "大二下", "大三上", "大三下", "大四上", "大四下"],
      termsMap: {
        "大一上": 0,
        "大一下": 1,
        "大二上": 2,
        "大二下": 3,
        "大三上": 4,
        "大三下": 5,
        "大四上": 6,
        "大四下": 7
      },
      rawGrade: [],
      termGrade: [],
      clickCount: 0,
    };
  },
  mounted() {
    const path = window.location.hash;
    const i = path.lastIndexOf("/");
    this.token = path.substring(i + 1, path.length);

    CheckStatus(this.token)
      .then((res) => {
        if (res.code !== 0) {
          ElMessage({
            message: res.message,
          })
          return;
        }
        if (res.data.hasTemp) {
          this.loginSuccess = true;
          this.rawGrade = res.data.gradeItems;
          this.setupShowGrade();
        } else {
          this.verifyCodeBase64 = res.data.verifyCodeImageBase64;
        }
      });

  },

  methods: {
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          let dto: QueryScoreDTO = {
            verifyCode: this.form.captcha,
            urpSystemPassword: this.form.password
          }
          GetScore(dto, this.token)
            .then(res => {
              if (res.code === 50003) {
                ElMessage({
                  message: res.message
                });
                this.refreshCaptcha();
                return;
              }

              if (res.code !== 0) {
                ElMessage({
                  message: res.message
                });
                return;
              }
              // console.log(res)
              this.rawGrade = res.data;
              this.loginSuccess = true;
              this.setupShowGrade();
            });

        } else {
          console.log('Validation failed');
          return false;
        }
      });
    },
    refreshCaptcha() {
      this.clickCount++;
      if (this.clickCount > 5) {
        alert("休息一下吧")
        setTimeout(() => {
          this.clickCount = 0;
        }, 4000)
        return
      }
      GetVerifyCodeImage(this.token)
        .then((res) => {
          if (res.code !== 0) {
            ElMessage({
              message: res.message
            });
            return;
          }
          this.verifyCodeBase64 = res.data.verifyCodeImageBase64;
        });
    },
    setupShowGrade() {
      let grades: { termName: string, grades: GradeVO[] }[] = [];
      this.terms.forEach((t: string) => {
        grades.push({termName: t, grades: []})
      })

      let rawGrade = this.rawGrade;
      rawGrade.forEach((g, i) => {
        grades[this.termsMap[g.term]].grades.push(g);
      })
      const map = {
        '必修': 0,
        '选修': 1,
        '任选': 2,
        'null': 2,
        'NULL': 2,
      }
      // console.log(grades);
      grades.forEach(gs => {
        gs.grades.sort((g1: GradeVO, g2: GradeVO) => {
          // console.log(g1+"   "+g2)
          return map[g1.properties] - map[g2.properties];
        });
      })

      this.termGrade = grades;
      console.log(grades)
    },
  }
}
</script>
<style scoped>
.score-container {
  padding: 5px;
}

.term-name {
  width: 100%;
  text-align: center;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5; /* 页面背景色 */
}

.login-form {
  width: 90%;
  max-width: 400px;
  background-color: #fff; /* 表单背景色 */
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  animation: slide-up 0.3s ease; /* 表单动画效果 */

  @keyframes slide-up {
    from {
      transform: translateY(20px);
      opacity: 0;
    }
    to {
      transform: translateY(0);
      opacity: 1;
    }
  }
}

.form-title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}

.captcha-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.captcha-img {
  margin-left: 10px;
  cursor: pointer;
  border-radius: 4px;
  transition: transform 0.3s ease; /* 图片悬停效果 */
}

.captcha-img:hover {
  transform: scale(1.1);
}

.submit-btn {
  width: 100%;
}


</style>
